var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var revUrlhash = require('gulp-rev-urlhash');
var cssmin = require('gulp-clean-css');
var less = require('gulp-less');
var cssver = require('gulp-make-css-url-version');
var uglify = require('gulp-uglify');
var spritesmith = require('gulp.spritesmith');
var nunjucks = require('gulp-nunjucks');
var htmlbeauty = require('gulp-html-beautify');
var nodemon = require('gulp-nodemon');
var htmlmin = require('gulp-htmlmin');
var fs = require('fs');
var path = require('path');
var Q = require('q');
var data = require('gulp-data');


var src = 'src';
var rootdir = (process.env.NODE_ENV == 'development') ? '../public' : '../public2'

var dist1 = `${rootdir}/dist`;
var htmldir = `${rootdir}/html`;


// html
gulp.task('html', () => {
    gulp.src(`${src}/html/**/*.html`)
        .pipe(data(file => {
            var pagename = path.basename(file.path);
            return {page_name: pagename};
        }))
        .pipe(nunjucks.compile({dist: './dist'}))
        .pipe(htmlbeauty({ indentSize: 2 }))
        .pipe(htmlmin({minifyJS: true, miniCSS: true}))
        .pipe(gulp.dest(`${htmldir}`));
});

// less 
gulp.task('less', () => {
    gulp.src(`${src}/less/**/*.less`)
        .pipe(less()) // 编译
        // .pipe(cssmin()) // 压缩
        .pipe(rename({ suffix: '.min' })) // 重命名 
        .pipe(gulp.dest(`${dist1}/css`))
        .pipe(cssver({})) // 背景图hash指纹化
        .pipe(gulp.dest(`${dist1}/css`))
        .pipe(revUrlhash()) // css 文件hash指纹化
        .pipe(revUrlhash.manifest('css.map.json'))
        .pipe(gulp.dest(`${dist1}/css`));
        
});


// js 
gulp.task('js', () => {
    gulp.src(`${src}/js/**/*.js`)
        // .pipe(uglify())
        .pipe(rename({ suffix: ".min" }))
        .pipe(gulp.dest(`${dist1}/js`))
        .pipe(revUrlhash())
        .pipe(revUrlhash.manifest('js.map.json'))
        .pipe(gulp.dest(`${dist1}/js`))
        .on('finish', () => {
            console.log(' .... ')
        });
});


// sprite
gulp.task('sprite', () => {
    var files = fs.readdirSync(`${src}/icons`);
    var _version = new Date().getTime();
    files.forEach((name) => { 
        var f = `${src}/icons/${name}`;
        var deferred = Q.defer();
        fs.stat(f, (err, stats) => {
            if (stats.isDirectory()) deferred.resolve(name);
        });
        deferred.promise.then((name) => {
            console.log(f);
            var opts = {
                imgName: `sprite-${name}.png`,
                cssName: `sprite-${name}.css`,
                padding: 10
            };
            var spriteData = gulp.src(`${f}/*.png`).pipe(spritesmith(opts));
            spriteData.img.pipe(gulp.dest(`${dist1}/css`));
            spriteData.css
                .pipe(replace(/^.icon-/gm, `.c${name}-`))
                .pipe(rename({ extname: '.less' }))
                .pipe(gulp.dest(`${src}/icons`));
            });
        
    });
});


// copy: img, lib
gulp.task('copy', () => {
    gulp.src(`${src}/images/**`).pipe(gulp.dest(`${dist1}/images`));
    gulp.src(`${src}/lib/**`).pipe(gulp.dest(`${dist1}/lib`));
});

gulp.task('watch', () => {
    gulp.watch(`${src}/html/**/*.html`, ['html']);
    gulp.watch(`${src}/less/**/*.less`, ['less']);
    gulp.watch(`${src}/js/**/*.js`, ['js']);
});

// webserver
gulp.task('webserver', () => {
    nodemon({
        script: 'index.js',
        ext: 'json js',
        watch: [`../public`, 'conf.json', 'index.js'],
        env: {
            PORT: 9090
        }
    });
});


// merge
gulp.task('merge', () => {
    // ...
});



// 
gulp.task('build', ['copy', 'html', 'less', 'js']);
gulp.task('dev', ['webserver', 'js', 'html', 'less', 'watch']);
console.log("\n\n http://localhost:9090\n\n");